%
% Created 11/01/12 Vasyl Mykhalchuk
%
function [resultCriticalPoints] = extractCriticalPoints(sField, adjVerticesList)

% maximum number of critical points NB substitute this hard-coded element
% with dynamic array
sizeN = size(sField);
kMaxCriticalPoints = sizeN(1);
criticalPointsTmp = zeros(kMaxCriticalPoints,1,'int32');
numberOfVertices = sizeN;

% the current number of feature/critical points found 
currentNumberOfCriticalPoints = 0;

for iVertex = 1:numberOfVertices
    if ( isCriticalPoint(iVertex, sField, adjVerticesList) )
        criticalPointsTmp(currentNumberOfCriticalPoints+1) = int32(iVertex);
        currentNumberOfCriticalPoints = currentNumberOfCriticalPoints + 1;
   end
end

if(currentNumberOfCriticalPoints~=0)
    resultCriticalPoints = zeros(currentNumberOfCriticalPoints,1, 'int32');
else
    resultCriticalPoints = 0;
end;%if

for i = 1:currentNumberOfCriticalPoints
    resultCriticalPoints(i) = criticalPointsTmp(i);
end

end

% ========================================================================
function [isCriticalPoint] = isCriticalPoint(iVertex, scalarField, adjVerticesList)
kTreshHold = 0.0000001;
isCriticalPoint = 0;
adjacentVertices = adjVerticesList(iVertex,:);
[x, length] = size(adjacentVertices);
i = 1;
if( scalarField(iVertex) >= 0)
while (i<length)
    if (adjacentVertices(i) ~= 0)
        if ( scalarField(iVertex) <= scalarField(adjacentVertices(i)) )
            i = length + 1;
        end%if inner
    end%if outer
    i = i + 1;
end%while
else
    while (i<length)
    if (adjacentVertices(i) ~= 0)
        if ( scalarField(iVertex) >= scalarField(adjacentVertices(i)) )
            i = length + 1;
        end%if inner
    end%if outer
    i = i + 1;
end%while
    
end%if
if ( (i == length) && (abs(scalarField(iVertex)) > kTreshHold)  )
    isCriticalPoint = 1;
end%if
%}

end%function isCriticalPoint